package com.rtf.framework.web.mvc.config.secure.configurer;

import com.rtf.framework.web.mvc.config.secure.configurer.support.AppAuthenticationExceptionEntryPoint;
import com.rtf.framework.web.mvc.config.secure.configurer.support.AppPostRequestMatcher;
import com.rtf.framework.web.mvc.config.secure.handler.AppAuthenticationHandlerDelegate;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.util.matcher.AndRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

/**
 * 请求访问被拒绝的处理
 */
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
public class AppWebSecureConfigurerAccessDenied extends AppWebSecureConfigurerAdaptor {

    @Override
    public boolean isEnable() {
        return true;
    }

    @Override
    public void doConfigure(HttpSecurity httpSecurity) throws Exception {
        log.debug("{} 配置安全策略" , getClass().getSimpleName());

        AppAuthenticationHandlerDelegate appAuthenticationHandlerDelegate =
                httpSecurity.getSharedObject( AppAuthenticationHandlerDelegate.class ) ;

        // 参考 DelegatingAuthenticationEntryPoint，对请求进行匹配
        RequestMatcher preferredMatcher = new AndRequestMatcher(Lists.newArrayList(
//                new RequestHeaderRequestMatcher("X-Requested-With", "XMLHttpRequest") ,
                new AppPostRequestMatcher()
        ));

        httpSecurity.exceptionHandling()
                .defaultAuthenticationEntryPointFor( new AppAuthenticationExceptionEntryPoint() , preferredMatcher)
                .accessDeniedHandler( appAuthenticationHandlerDelegate ) ;
    }

}
